// src/pages/Profile.tsx
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getProfile } from '../services/api';

// 定义用户类型
interface User {
    id: number;
    username: string;
    email: string;
    role: string;
}

const Profile: React.FC = () => {
    const navigate = useNavigate();
    const [user, setUser] = useState<User | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');

    // 获取用户信息
    useEffect(() => {
        const fetchUserProfile = async () => {
            try {
                // 从localStorage获取token并传递给getProfile
                const token = localStorage.getItem('token');
                if (!token) {
                    throw new Error('未找到登录信息，请重新登录');
                }
                const response = await getProfile(token);
                setUser(response.data.user);
            } catch (err: any) {
                setError(err.response?.data?.error || '获取个人信息失败');
                // 出错后跳回登录页
                setTimeout(() => {
                    navigate('/login');
                }, 2000);
            } finally {
                setLoading(false);
            }
        };

        fetchUserProfile();
    }, [navigate]);

    // 退出登录
    const handleLogout = () => {
        localStorage.removeItem('token');
        navigate('/login');
    };

    if (loading) {
        return <div className="loading">加载中...</div>;
    }

    if (error) {
        return <div className="error">{error}</div>;
    }

    return (
        <div className="profile-container">
            <h2>个人信息</h2>
            {user && (
                <div className="profile-info">
                    <p>ID: {user.id}</p>
                    <p>用户名: {user.username}</p>
                    <p>邮箱: {user.email}</p>
                    <p>角色: {user.role}</p>
                </div>
            )}
            <div className="profile-actions">
                <button
                    className="btn"
                    onClick={() => navigate('/update-password')}
                >
                    修改密码
                </button>
                <button
                    className="btn logout-btn"
                    onClick={handleLogout}
                >
                    退出登录
                </button>
            </div>
        </div>
    );
};

export default Profile;